package com.yj.agent.util;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AESUtils {
//
//    public static void main(String [] args) throws Exception{
//
//        String key = "izUxyta7f7jHqmS9";
//        // {"gamerId":"1568","isMgr":"Y"}
////        String content = "{\"gamerId\":\"1589\",\"isMgr\":\"Y\"}";
//        String content = "837NAEw/V5GM+AtcmT0ksor7GS1zoe+3vNsEmS/IjFI=";
//        System.out.println(decrypt(content,key,key));
//    }

    public static String encrypt(String data, String sKey, String ivParameter) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec skeySpec = new SecretKeySpec(sKey.getBytes("UTF-8"), "AES");
        int blockSize = cipher.getBlockSize();
        byte[] dataBytes = data.getBytes("UTF-8");
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength += blockSize - plaintextLength % blockSize;
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
        cipher.init(1, skeySpec, new IvParameterSpec(ivParameter.getBytes("UTF-8")));
        byte[] encrypted = cipher.doFinal(plaintext, 0, plaintext.length);
        String rs = Base64.encodeBase64String(encrypted);
        rs = rs.replace("+", "-").replace("/", "_");
        return rs;
    }

    public static String decrypt(String sSrc, String sKey, String ivParameter) throws Exception {
        try {
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes("UTF-8"));
            cipher.init(2, skeySpec, iv);
            sSrc = sSrc.replace("-", "+").replace("_", "/");
            byte[] encrypted1 = Base64.decodeBase64(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "UTF-8");
            return originalString;
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }


}